import { OPERATION_STATES, POWER_STATES } from '@/constants/Command'
import { getNoopActions, injectState } from '@/controller/base/index'
import type { BaseController } from '../BaseAppliance/definition'
import { BaseActions, createBaseState } from '../BaseAppliance/index'
import { merge } from 'lodash'
import { DemoProgramActions, getDemoDetailOptions, setDemoProgramState } from './common/Program'
import { DetailScene } from '../BaseAppliance/constants'
import type { ApplianceDetail, ApplianceProgram } from '@/api/appliance'
import type { DemoDatasource } from '@/demo/types'

export const createDemoBaseState: () => BaseController.State = () =>
  injectState(createBaseState, (state) => {
    state.detailScene = DetailScene.VirtualAppliance
    state.powerState = POWER_STATES.ON
    state._datasource.loaded = true
    state._datasource.loadSuccess = true
  })

export const DemoBaseActions: BaseController.Actions = {
  ...merge(getNoopActions(BaseActions), DemoProgramActions),
  async togglePowerState() {
    // 点击【关闭家电】按钮 只切回Ready状态
    this.operationState = OPERATION_STATES.READY
    // this.powerState = this.powerState === POWER_STATES.ON ? POWER_STATES.STANDBY : POWER_STATES.ON
  },
}

export function setDemoBaseState(state: BaseController.State, demoOptions: DemoDatasource) {
  const { settings, commands } = demoOptions
  const demoDetail = getDemoDetail(demoOptions)
  state._datasource.detail = demoDetail
  state._datasource.brand = demoDetail.brand
  state._datasource.type = demoDetail.type
  state._datasource.haId = demoDetail.haId
  state._datasource.vib = demoDetail.vib
  state._datasource.settings = settings
  state._datasource.commands = commands
  if (demoDetail.programKey) setDemoProgramState(state, demoOptions)
}

export function getDemoDetail(demoOptions: DemoDatasource, program?: ApplianceProgram.Scope | string): ApplianceDetail {
  const { detail, available } = demoOptions
  let programKey = ''
  if (!program) {
    programKey = detail.programKey || ''
  } else {
    programKey = typeof program === 'string' ? program : program.key
  }

  let detailOption = null
  if (programKey) {
    const currentAvailable = available[programKey]
    if (currentAvailable) {
      detailOption = getDemoDetailOptions(currentAvailable)
    }
  }
  return {
    ...detail,
    option: detailOption,
  }
}
